{% extends 'web/layout/manage.html' %}
{% load static %}

{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-file-progress {
            position: fixed;
            right: 20px;
            bottom: 2px;
            width: 400px;
        }

        .progress-error {
            color: red;
        }
    </style>

{% endblock %}

{% block content %}
    {#    面板带表格#}
    <div class="panel panel-default">
        <div class="panel-heading">
            <div>
                <h3 class="panel-title">
                    <a style="cursor: pointer" href="{% url 'file' project_id=request.login_user.project.id %}">
                        <i class="fa fa-home"></i>
                        <span>文件库</span>
                    </a>
                    {% for bread_crumb in bread_crumb_list %}
                        <a style="cursor: pointer"
                           href="{% url 'file' project_id=request.login_user.project.id %}?folder_id={{ bread_crumb.id }}">
                            <i class="fa fa-chevron-right"></i>
                            <span>{{ bread_crumb.name }}</span>
                        </a>
                    {% endfor %}
                </h3>
            </div>
            <div class="function">
                <div class="btn btn-primary btn-xs upload" style="position: relative">
                    <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                    <input type="file" multiple name="uploadFile" id="uploadFile">
                </div>
                <button type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#addFolderModal"
                        data-whatever="新建文件夹">
                    <i class="fa fa-plus-circle" aria-hidden="true"></i>新建文件夹
                </button>
            </div>
        </div>
        <div class="panel-body">
            <table class="table">
                <thead>
                <tr>
                    <th>文件名</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="rowList">
                {% for file in file_list %}
                    <tr>
                        <td>
                            {% if file.file_type == 1 %}
                                <a href="{{ file.file_path }}" target="_blank">
                                    <i class="fa fa-file"></i>
                                    <span>{{ file.name }}</span>
                                </a>
                            {% else %}
                                <a href="{% url 'file' project_id=request.login_user.project.id %}?folder_id={{ file.id }}">
                                    <i class="fa fa-folder"></i>
                                    <span>{{ file.name }}</span>
                                </a>
                            {% endif %}
                        </td>
                        <td>
                            {% if file.file_type == 1 %}
                                {{ file.file_size }}
                            {% else %}
                                -
                            {% endif %}
                        </td>
                        <td>{{ file.update_user.username }}</td>
                        <td>{{ file.update_datetime }}</td>
                        <td>
                            {% if file.file_type == 2 %}
                                <a class="btn btn-default btn-xs"
                                   data-toggle="modal"
                                   data-target="#addFolderModal"
                                   data-whatever="编辑文件夹"
                                   data-name="{{ file.name }}"
                                   data-edit-folder-id="{{ file.id }}">
                                    <i class="fa fa-edit"></i>
                                </a>
                            {% else %}
                                <a href="{% url 'file_download' project_id=request.login_user.project.id file_id=file.id %}"
                                   class="btn btn-default btn-xs">
                                    <i class="fa fa-cloud-download"></i>
                                </a>
                            {% endif %}
                            <a class="btn btn-danger btn-xs"
                               data-toggle="modal"
                               data-target="#deleteFolderModal"
                               data-delete-folder-id="{{ file.id }}">
                                <i class="fa fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    {#    新建文件夹模态框#}
    <div class="modal fade" tabindex="-1" role="dialog" id="addFolderModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <form id="addFolderForm">
                        {% csrf_token %}
                        <input type="hidden" id="edit-folder-id" name="edit-folder-id">
                        {% for field in add_file_form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg"></span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
                    <button type="button" class="btn btn-primary" id="addFolderSubmit">创 建</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    {#    删除文件模态框#}
    <div class="modal fade" tabindex="-1" role="dialog" id="deleteFolderModal">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>确定要删除文件夹吗？</h4>
                <p>文件夹下的所有文件也会被删除.</p>
                <p style="text-align: right">
                    <button type="button" class="btn btn-danger" id="deleteFolderBtn">删 除</button>
                    <button type="button" class="btn btn-default">取 消</button>
                </p>
            </div>
        </div>
    </div>
    {#    上传文件进度条展示#}
    <div class="upload-file-progress hide" id="progress-container">
        <div class="panel panel-default">
            <div class="panel-body">
                <table class="table">
                    <tbody id="progressList">

                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {#    上传文件进度条模板#}
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div id="progress-content" class="progress-bar progress-bar-success progress-bar-striped"
                             role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100" style="width: 0%;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    {#    上传文件成功后返回的模板#}
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <a href="" class="name-href">
                        <span class="name"></span>
                    </a>
                </td>
                <td class="file_size"></td>
                <td class="username"></td>
                <td class="datetime"></td>
                <td>
                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#deleteFolderModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>

{% endblock %}

{% block js %}
    <script src="{% static 'web/js/cos-js-sdk-v5.min.js' %}"></script>
    <script>

        var FOLDER_URL = '{% url 'file' project_id=request.login_user.project.id %}';
        var DELETE_FOLDER_URL = '{% url 'file_delete' project_id=request.login_user.project.id %}';
        var COS_CREDENTIAL_URL = '{% url 'cos_credential' project_id=request.login_user.project.id %}'
        var FILE_POST_URL = '{% url 'file_post' project_id=request.login_user.project.id %}'
        var CURRENT_FOLDER_ID = "{{ folder_object.id }}";

        $(function () {
            initAddModal();
            addFolder();
            deleteFolder();
            uploadFile();
        });

        /*
        * 给bootstrap模态对话框添加事件
        * */
        function initAddModal() {
            $('#addFolderModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var recipient = button.data('whatever')
                var name = button.data('name')
                var editFolderId = button.data('edit-folder-id')
                var modal = $(this)
                modal.find('.modal-title').text(recipient)

                if (editFolderId) {
                    // 编辑操作
                    modal.find('#id_name').val(name)
                    $('#edit-folder-id').val(editFolderId)
                } else {
                    // 添加操作
                    $('span.error-msg').empty()
                    // 原生js操作dom元素
                    //document.getElementById('addFolderForm').reset()
                    // jquery操作dom元素
                    $('#addFolderForm')[0].reset()
                }
            });
            $('#deleteFolderModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var deleteFolderId = button.data('delete-folder-id')
                $('#deleteFolderBtn').attr('fid', deleteFolderId)
            })
        }

        /*
        * 新建文件夹按钮绑定事件
        * */
        function addFolder() {
            $('#addFolderSubmit').click(function () {
                $.ajax({
                    /*
                    给get请求的路径发送post请求
                    in browse console:
                    >location.href
                    >"http://127.0.0.1:8000/manage/5/file/?folder_id=2"
                    如果不用location.href就需要拼接url
                    */
                    url: location.href,
                    type: 'POST',
                    data: $('#addFolderForm').serialize(),
                    dataType: 'JSON',
                    success: function (res) {
                        console.log(res);
                        if (res.status) {
                            location.href = location.href
                        } else {
                            console.log(res.error);
                            $.each(res.error, function (key, value) {
                                $('#id_' + key).next().text(value[0])
                            })
                        }
                    }
                })
            })
        }

        /*
        * 删除文件夹按钮绑定事件
        * */
        function deleteFolder() {
            $('#deleteFolderBtn').click(function () {
                $.ajax({
                    url: DELETE_FOLDER_URL,
                    type: 'GET',
                    data: {
                        deleteFolderId: $(this).attr('fid')
                    },
                    dataType: 'JSON',
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href
                        } else {
                            alert('URL不合法')
                        }
                    }
                })
            })
        }

        /*
        * 上传文件按钮绑定事件
        * */
        function uploadFile() {
            $('#uploadFile').change(function () {

                    // 每次上传前清空所有的进度条
                    $('#progressList').empty()
                    // 选择上传后才能显示上传进度条
                    $('#progress-container').removeClass('hide')
                    // 获取上传的文件对象
                    fileList = $(this)[0].files
                    // 获取本次上传的每个文件名称 & 大小
                    var checkFileList = [];
                    $.each(fileList, function (index, fileObject) {
                        checkFileList.push({
                            name: fileObject.name,
                            size: fileObject.size // 单位是B 字节
                        })
                    })
                    // 本次上传的每个文件的名称 & 大小传递给后端，进行校验
                    var COS_OBJECT = new COS({
                        getAuthorization: function (options, callback) {
                            // 给django后台发送请求，获取临时凭证
                            // $.ajax({type:"GET"})
                            $.post(COS_CREDENTIAL_URL, JSON.stringify(checkFileList), function (res) {
                                if (res.status) {
                                    var credentials = res.data && res.data.credentials;
                                    if (!res.data || !credentials) return console.error('credentials invalid');
                                    callback({
                                        TmpSecretId: credentials.tmpSecretId,
                                        TmpSecretKey: credentials.tmpSecretKey,
                                        XCosSecurityToken: credentials.sessionToken,
                                        StartTime: res.data.startTime,
                                        ExpiredTime: res.data.expiredTime,
                                    });
                                } else {
                                    alert(res.error + ', 请购买会员!')
                                }
                            });
                        }
                    });
                    $.each(fileList, function (index, fileObject) {
                        var fileName = fileObject.name;
                        var fileSize = fileObject.size;
                        // 给上传的文件定义一个key，为了保证用户上传的同名文件不被覆盖，自定义key
                        var key = (new Date()).getTime() + '_' + fileName
                        // 每个文件都需要有一个上传进度条
                        var tr = $('#progressTemplate').find('tr').clone()
                        tr.find('.name').text(fileName)
                        $('#progressList').append(tr)
                        // 异步上传文件
                        // COS_OBJECT上传文件时候才会触发，虽然放在全局变量的位置，但不会直接触发
                        // COS_OBJECT内部会检测临时密钥的过期时间，如果超出有效期，会自动往后台发送请求，并更新临时密钥
                        COS_OBJECT.putObject({
                                Bucket: '{{ request.login_user.project.bucket_name }}',
                                Region: '{{ request.login_user.project.bucket_region }}',
                                Key: key,
                                StorageClass: 'STANDARD',
                                Body: fileObject,
                                onProgress: function (progressDate) {
                                    console.log("文件上传进度--->", fileName, progressDate);
                                    var percent = progressDate.percent * 100 + '%'
                                    tr.find('#progress-content').text(percent)
                                    tr.find('#progress-content').css('width', percent)
                                    // 文件上传进度---> basic.jpg
                                    // { loaded: 252860 percent: 1 speed: 524605.81 total: 252860 }
                                }
                            }, function (err, data) {
                                console.log(err || data);
                                /*  data 的数据格式：
                                    ETag: ""9c83f920caa6defe2843565146f03318""
                                    Location: "13020868780-1652838235-1300450009.cos.ap-beijing.myqcloud.com/basic.jpg"
                                    RequestId: "NjI4NDUxY2NfNjVjZjM4MGJfNjcwZF82MzYwZjgw"
                                    statusCode: 200
                                * */
                                if (data && data.statusCode === 200) {
                                    // 上传成功
                                    // 每上传成功一个文件后就给后台发送一个请求将信息发送到数据库中
                                    $.post(FILE_POST_URL, {
                                        name: fileName,
                                        key: key,
                                        file_size: fileSize,
                                        parent: CURRENT_FOLDER_ID,
                                        etag: data.ETag,
                                        file_path: data.Location
                                    }, function (res) {
                                        // 在数据库中写入成功，将已添加的数据在页面上动态展示。
                                        console.log(res);
                                        var newTr = $('#rowTpl').find('tr').clone();
                                        newTr.find('.name').text(res.data.name);
                                        newTr.find('.name-href').attr('href',res.data.file_path);
                                        newTr.find('.file_size').text(res.data.file_size);
                                        newTr.find('.username').text(res.data.username);
                                        newTr.find('.datetime').text(res.data.datetime);
                                        newTr.find('.delete').attr('data-fid', res.data.id);
                                        newTr.find('.download').attr('href', res.data.download_url);

                                        $('#rowList').append(newTr);
                                        // 自己的进度删除
                                        tr.remove();
                                    })
                                } else {
                                    // 上传失败
                                    tr.find('.progress-error').text('文件上传失败!')
                                }
                            }
                        )
                    })
                }
            )
        }

    </script>
{% endblock %}